//
//  BluetoothManager.swift
//  newSwift
//
//  Created by Li on 2023/12/11.
//

import Foundation
import CoreBluetooth

/// 日志输出
func BLEDebug(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
    print(items, separator: separator, terminator: terminator)
#endif
}

/// 蓝牙名称过滤类型
enum BLENameFilter {
    /// 前缀
    case preFix(String)
    /// 后缀缀
    case subFix(String)
    /// 包含
    case containsFix(String)
}

class BluetoothManager: NSObject {
    
    /// 单例
    static let shared = BluetoothManager()
    /// 中心
    var centralManager: CBCentralManager?
    /// 扫描蓝牙设备的名称过滤前缀
    var namefilter: BLENameFilter?
    
    /// 扫描到设备的回调
    var discoverPeripheralCallBack: ((BLEDevice)->(Void))?
    var discoverPeripheralArray: [CBPeripheral] = []
    
    override init() {
        super.init()
        self.centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    /// 扫描设备
    func scan() {
        BLEDebug("开始扫描设备")
        discoverPeripheralArray.removeAll()
        centralManager?.scanForPeripherals(withServices: nil, options: nil)
    }
    
    /// 停止扫描
    func stopScan() {
        centralManager?.stopScan()
    }
    
}

extension BluetoothManager: CBCentralManagerDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown,
                .resetting,
                .unsupported,
                .unauthorized: // 未授权 / 未知错误等
            BLEDebug("未授权 / 未知错误等")
        case .poweredOn:
//            scan() // 开始扫描
            BLEDebug("蓝牙功能正常")
        case .poweredOff:
            stopScan() // 结束扫描
            
        default: // 默认是错误
            BLEDebug("其他错误")
        }
    }
    
    /// 扫描到设备
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        
        guard let name = peripheral.name else { return  }
        
        if namefilter != nil {
            switch namefilter {
            case .preFix(let filterString):
                if !name.hasPrefix(filterString) { return }
            case .subFix(let filterString):
                if !name.hasSuffix(filterString) { return }
            case .containsFix(let filterString):
                if !name.contains(filterString) { return }
            default:
                BLEDebug("")
            }

        }
        
        /// 从广播中拿mac地址
        var mac: String?
        
        if let manufactData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
//            BLEDebug(manufactData)
            if manufactData.bytes.count >= 6 {
                mac =  manufactData.subdata(in: Range(NSMakeRange(0, 6))!).map { String(format: "%02x", $0) }
                    .joined(separator: ":").uppercased()
            }
            
        }
        
        let device = BLEDevice()
        device.peripheral = peripheral
        device.macAddress = mac
        
        let arr = discoverPeripheralArray.filter{ $0.identifier == peripheral.identifier }
        if arr.isEmpty {
            discoverPeripheralCallBack?(device)
        }
        
        
    }
    
}


/// 封装蓝牙对象

class BLEDevice {
    
    /// 蓝牙外设对象
    var peripheral: CBPeripheral?
    /// mac地址
    var macAddress: String?
    /// 可写特征 COMMAND
    var writeCharacteristic: CBCharacteristic?
    /// 可读特征 INFO
    var readCharacteristic: CBCharacteristic?
    /// 通知特征 DATA
    var notifyCharacteristic: CBCharacteristic?
    /// 读写特征 VER_MAC
    var readWriteCharacteristic: CBCharacteristic?
    
    init() {
       
    }
}
